package com.molichuxing.gateway.bff.goods.services.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.molichuxing.services.infrastructure.service.*;
import com.molichuxing.services.property.GoodsTypeIntroduceEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.utils.DateUtil;
import com.molichuxing.gateway.bff.basic.entity.response.VehicleMakeVo;
import com.molichuxing.gateway.bff.goods.convertor.Convert;
import com.molichuxing.gateway.bff.goods.entity.response.GoodsAppConfirmDetailVo;
import com.molichuxing.gateway.bff.goods.entity.response.GoodsAppDetailVo;
import com.molichuxing.gateway.bff.goods.entity.response.GoodsBigScreenDrawerMileageVo;
import com.molichuxing.gateway.bff.goods.entity.response.GoodsBigScreenDrawerPackageVo;
import com.molichuxing.gateway.bff.goods.entity.response.GoodsBigScreenDrawerSpecVo;
import com.molichuxing.gateway.bff.goods.entity.response.GoodsBigScreenVo;
import com.molichuxing.gateway.bff.goods.entity.response.GoodsConfirmVo;
import com.molichuxing.gateway.bff.goods.entity.response.GoodsDrawerMileageVo;
import com.molichuxing.gateway.bff.goods.entity.response.GoodsDrawerPackageVo;
import com.molichuxing.gateway.bff.goods.entity.response.GoodsExclusiveDrawerVo;
import com.molichuxing.gateway.bff.goods.entity.response.GoodsIntroduceVo;
import com.molichuxing.gateway.bff.goods.entity.response.GoodsPurchaseVo;
import com.molichuxing.gateway.bff.goods.entity.response.GoodsReletVo;
import com.molichuxing.gateway.bff.goods.entity.response.GoodsRenewVo;
import com.molichuxing.gateway.bff.goods.entity.response.GoodsSubscribeDrawerVo;
import com.molichuxing.gateway.bff.goods.entity.response.GoodsVo;
import com.molichuxing.gateway.bff.goods.services.GoodsBffService;
import com.molichuxing.gateway.bff.orders.entity.response.CostDetailsVo;
import com.molichuxing.gateway.contants.OrderConst;
import com.molichuxing.gateway.exception.GoodsExceptionCodeEnum;
import com.molichuxing.gateway.property.OrderCreateTypeEnum;
import com.molichuxing.gateway.property.PowerTypeEnum;
import com.molichuxing.services.business.dto.response.CarDetailBizDto;
import com.molichuxing.services.business.dto.response.GoodsBigScreenBizDto;
import com.molichuxing.services.business.dto.response.GoodsBizBizDto;
import com.molichuxing.services.business.dto.response.GoodsMileagePackageReletBizDto;
import com.molichuxing.services.business.dto.response.GoodsOrderBizDto;
import com.molichuxing.services.business.dto.response.GoodsReletMileageBizDto;
import com.molichuxing.services.business.dto.response.OrderSubscribeBizDto;
import com.molichuxing.services.business.dto.response.StoreInfoBizDto;
import com.molichuxing.services.business.dto.response.VehicleBizDto;
import com.molichuxing.services.business.dto.response.VehicleNameBizDto;
import com.molichuxing.services.business.service.CarBizService;
import com.molichuxing.services.business.service.GoodsBizService;
import com.molichuxing.services.business.service.OrderBizService;
import com.molichuxing.services.business.service.OrderSubscribeBizService;
import com.molichuxing.services.business.service.StoreBizService;
import com.molichuxing.services.business.service.VehicleBizService;
import com.molichuxing.services.infrastructure.dto.response.GoodsIntroduceDto;
import com.molichuxing.services.infrastructure.dto.response.StoreDto;
import com.molichuxing.services.infrastructure.dto.response.VehicleDto;
import com.molichuxing.services.infrastructure.dto.response.VehicleMakeDto;
import com.molichuxing.services.infrastructure.dto.response.VehicleModelParamDto;
import com.molichuxing.services.infrastructure.dto.response.VehiclePictureDto;
import com.molichuxing.services.property.GoodsMileageSubscribeEnum;
import com.molichuxing.services.property.GoodsTypeEnum;

/**
 * 商品信息相关bff
 * 
 * @author yixuelin
 * @date 2019年8月13日
 *
 */
@Service("goodsBffService")
public class GoodsBffServiceImpl implements GoodsBffService {
	private static final Logger logger = LoggerFactory.getLogger(GoodsBffServiceImpl.class);

	@Resource
	private GoodsBizService goodsBizService;

	@Resource
	private VehicleService vehicleService;

	@Resource
	private StoreBizService storeBizService;

	@Resource
	private VehicleModleService vehicleModleService;

	@Resource
	private VehiclePictureService vehiclePictureService;


	@Resource
    private VehicleParamService vehicleParamService;

	@Resource
	private OrderSubscribeBizService orderSubscribeBizService;

	@Resource
	private VehicleBizService vehicleBizService;

	@Resource
	private VehicleMakeService vehicleMakeService;

	@Resource
	private CarBizService carBizService;

	@Resource
	private StoreService storeService;

	@Resource
    private OrderBizService orderBizService;

	@Resource
    private GoodsIntroduceService goodsIntroduceService;

	@Resource
	private IovCarService iovCarService;

    @Override
    public Boolean isProhibited(Integer goodsId, Integer storeId) throws Exception {
		Boolean result = null;
		StoreInfoBizDto storeInfoBizDto = storeBizService.getStoreInfo(storeId);
        if(null == storeInfoBizDto) {
            return null;
        }
		result = goodsBizService.isProhibited(goodsId, storeInfoBizDto.getDealerId());

		if (result) {
			logger.info("[isProhibited]商品(" + goodsId + ")未绑定或下架");
			throw new BizException(GoodsExceptionCodeEnum.PROHIBITION.getCode(),
					GoodsExceptionCodeEnum.PROHIBITION.getMessage());
		}

		return result;
    }

    @Override
	public Paged<GoodsVo> getAppGoodsList(Integer storeId, Integer pageNum, Integer pageSize) throws Exception {
		//获取经销商信息
		StoreInfoBizDto storeInfoBizDto = storeBizService.getStoreInfo(storeId);
		if(null == storeInfoBizDto) {
            throw new BizException("门店信息不存在");
		}
		Paged<GoodsBizBizDto> page = goodsBizService.getAppGoodsList(storeInfoBizDto.getDealerId(), pageNum, pageSize);
		List<GoodsBizBizDto> goodsList = page.getList();
		Map<Integer, VehicleDto> vehicleMap = new HashMap<>();
		Map<Integer, String> vehicleImgMap = new HashMap<>();
        Map<Integer, List<VehicleModelParamDto>> vehicleParamMap = new HashMap<>();
		if(null != goodsList && goodsList.size() > 0) {
			for(GoodsBizBizDto goodsBizBizDto : goodsList) {
				VehicleDto vehicleDto = vehicleService.getVehicleByVehicleId(goodsBizBizDto.getVehicleStyleId());
				String vehicleFullName = vehicleBizService.getVehicleName(goodsBizBizDto.getVehicleStyleId());
				if(null != vehicleFullName) {
					vehicleDto.setName(vehicleFullName);
				}
				List<VehiclePictureDto> vehiclePictureDtoList = vehiclePictureService.getVehiclePictureByVehicleId(goodsBizBizDto.getVehicleStyleId());
				if (vehiclePictureDtoList != null && vehiclePictureDtoList.size() > 0) {
					vehicleImgMap.put(goodsBizBizDto.getGoodsId(), vehiclePictureDtoList.get(0).getServerUrl());
				}
				vehicleMap.put(goodsBizBizDto.getGoodsId(), vehicleDto);
                vehicleParamMap.put(goodsBizBizDto.getGoodsId(), vehicleParamService.getParamByModelId(goodsBizBizDto.getVehicleStyleId(), Arrays.asList("NEDC续航里程（km）", "快充时间（h）"), null));
			}
		}
		return Convert.toGoodsPage(page, vehicleMap, vehicleImgMap, vehicleParamMap);
	}

	@Override
	public Paged<GoodsVo> getAppGoodsListNew(Integer storeId,Map<String, Object> selectParam, Integer sortFlag, Integer pageNum, Integer pageSize) throws Exception {
		//获取经销商信息
		StoreInfoBizDto storeInfoBizDto = storeBizService.getStoreInfo(storeId);
		if(null == storeInfoBizDto) {
			throw new BizException("门店信息不存在");
		}
		Paged<GoodsBizBizDto> page = goodsBizService.getAppGoodsListNew(storeInfoBizDto.getDealerId(), selectParam, sortFlag, pageNum, pageSize);
		List<GoodsBizBizDto> goodsList = page.getList();
		Map<Integer, VehicleDto> vehicleMap = new HashMap<>();
		Map<Integer, String> vehicleImgMap = new HashMap<>();
		Map<Integer, List<VehicleModelParamDto>> vehicleParamMap = new HashMap<>();
		if(null != goodsList && goodsList.size() > 0) {
			for(GoodsBizBizDto goodsBizBizDto : goodsList) {
				VehicleDto vehicleDto = vehicleService.getVehicleByVehicleId(goodsBizBizDto.getVehicleStyleId());
				String vehicleFullName = vehicleBizService.getVehicleName(goodsBizBizDto.getVehicleStyleId());
				if(null != vehicleFullName) {
					vehicleDto.setName(vehicleFullName);
				}
				List<VehiclePictureDto> vehiclePictureDtoList = vehiclePictureService.getVehiclePictureByVehicleId(goodsBizBizDto.getVehicleStyleId());
				if (vehiclePictureDtoList != null && vehiclePictureDtoList.size() > 0) {
					vehicleImgMap.put(goodsBizBizDto.getGoodsId(), vehiclePictureDtoList.get(0).getServerUrl());
				}
				vehicleMap.put(goodsBizBizDto.getGoodsId(), vehicleDto);
				vehicleParamMap.put(goodsBizBizDto.getGoodsId(), vehicleParamService.getParamByModelId(goodsBizBizDto.getVehicleStyleId(), Arrays.asList("NEDC续航里程（km）", "快充时间（h）"), null));
			}
		}
		return Convert.toGoodsPage(page, vehicleMap, vehicleImgMap, vehicleParamMap);
	}

	@Override
    public List<GoodsVo> getSellWellGoodsList() throws Exception {
        List<Integer> goodsIds = orderBizService.getStatisticsGoods();
        if((null == goodsIds)||(goodsIds.size() == 0)) {
            return null;
        }
        List<GoodsBizBizDto> goodsList = goodsBizService.getAppGoodsByIds(goodsIds);
        Map<Integer, VehicleDto> vehicleMap = new HashMap<>();
		Map<Integer, String> vehicleImgMap = new HashMap<>();
        Map<Integer, List<VehicleModelParamDto>> vehicleParamMap = new HashMap<>();
        if(null != goodsList && goodsList.size() > 0) {
            for(GoodsBizBizDto goodsBizBizDto : goodsList) {
                VehicleDto vehicleDto = vehicleService.getVehicleByVehicleId(goodsBizBizDto.getVehicleStyleId());
				String vehicleFullName = vehicleBizService.getVehicleName(goodsBizBizDto.getVehicleStyleId());
				if(null != vehicleFullName) {
					vehicleDto.setName(vehicleFullName);
				}
                vehicleMap.put(goodsBizBizDto.getGoodsId(), vehicleDto);
				List<VehiclePictureDto> vehiclePictureDtoList = vehiclePictureService.getVehiclePictureByVehicleId(goodsBizBizDto.getVehicleStyleId());
				if (vehiclePictureDtoList != null && vehiclePictureDtoList.size() > 0) {
					vehicleImgMap.put(goodsBizBizDto.getGoodsId(), vehiclePictureDtoList.get(0).getServerUrl());
				}
                vehicleParamMap.put(goodsBizBizDto.getGoodsId(), vehicleParamService.getParamByModelId(goodsBizBizDto.getVehicleStyleId(), Arrays.asList("NEDC续航里程（km）", "快充时间（h）"), null));
            }
        }
        return Convert.toGoodsVo(goodsList, vehicleMap, vehicleImgMap, vehicleParamMap);
    }


    @Override
    public GoodsAppDetailVo getAppGoods(Integer goodsId, Integer packageId) throws Exception {
        GoodsOrderBizDto goodsAppDto = goodsBizService.getGoodsForOrder(goodsId, packageId);
        if(null == goodsAppDto) {
            return null;
        }
        VehicleDto vehicleDto = vehicleService.getVehicleByVehicleId(goodsAppDto.getVehicleStyleId());
		String vehicleFullName = vehicleBizService.getVehicleName(goodsAppDto.getVehicleStyleId());
		if(null != vehicleFullName) {
			vehicleDto.setName(vehicleFullName);
		}
		List<VehiclePictureDto> vehiclePictureDtoList = vehiclePictureService.getVehiclePictureByVehicleId(goodsAppDto.getVehicleStyleId());
        List<VehicleModelParamDto> paramList = vehicleParamService.getParamByModelId(goodsAppDto.getVehicleStyleId(), Arrays.asList("NEDC续航里程（km）", "快充时间（h）"), null);
		GoodsAppDetailVo goodsAppDetailVo = Convert.toGoodsAppDetailVo(goodsAppDto, vehicleDto, paramList);
		if (vehiclePictureDtoList != null && vehiclePictureDtoList.size() > 0) {
			if (null != vehiclePictureDtoList.get(0).getServerUrl()) {
				goodsAppDetailVo.setModelImg(vehiclePictureDtoList.get(0).getServerUrl());
			}
		}
		List<GoodsIntroduceDto> goodsIntroduceList = goodsIntroduceService.getGoodsIntroduce(GoodsTypeIntroduceEnum.getName(goodsAppDto.getGoodsType()));
        Convert.toGoodsIntroduceVo(goodsIntroduceList, goodsAppDetailVo);
	    return goodsAppDetailVo;
    }

	@Override
	public GoodsAppConfirmDetailVo getAppConfirmGoods(Integer goodsId, Integer packageId) throws Exception {
		GoodsOrderBizDto goodsAppDto = goodsBizService.getGoodsForOrder(goodsId, packageId);
		if(null == goodsAppDto) {
			return null;
		}
		VehicleDto vehicleDto = vehicleService.getVehicleByVehicleId(goodsAppDto.getVehicleStyleId());
		List<VehicleModelParamDto> paramList = vehicleParamService.getParamByModelId(goodsAppDto.getVehicleStyleId(), Arrays.asList("NEDC续航里程（km）", "快充时间（h）"), null);
		GoodsAppConfirmDetailVo result = Convert.toGoodsAppConfirmDetailVo(goodsAppDto, vehicleDto, paramList);
		List<VehiclePictureDto> vehiclePictureDtoList = vehiclePictureService.getVehiclePictureByVehicleId(goodsAppDto.getVehicleStyleId());
		if (vehiclePictureDtoList != null && vehiclePictureDtoList.size() > 0) {
			if (null != vehiclePictureDtoList.get(0).getServerUrl()) {
				result.setModelImg(vehiclePictureDtoList.get(0).getServerUrl());
			}
		}
		String vehicleName = vehicleBizService.getVehicleName(goodsAppDto.getVehicleStyleId());
		if(null != vehicleName) {
			result.setVehicleStyleStr(vehicleName);
		}

		VehicleNameBizDto vehicleNameBizDto = vehicleBizService.getCarByModel(goodsAppDto.getVehicleStyleId());
		if(null != vehicleNameBizDto) {
			result.setVehicleStyleOne(vehicleNameBizDto.getSubBrandName() + " " + vehicleNameBizDto.getSeriesName());
			result.setVehicleStyleSecond(vehicleNameBizDto.getYear()+" "+vehicleNameBizDto.getModelName());
		}

		return result;
	}

	@Override
	public GoodsExclusiveDrawerVo getAppExclusiveGoods(Integer goodsId, Integer storeId) throws Exception {
        //获取经销商信息
        StoreInfoBizDto storeInfoBizDto = storeBizService.getStoreInfo(storeId);
        if(null == storeInfoBizDto) {
            return null;
        }
		GoodsExclusiveDrawerVo goodsExclusiveDrawer = Convert.toGoodsExclusiveDrawerVo(goodsBizService.getAppExclusiveGoods(goodsId, storeInfoBizDto.getDealerId()));
		if(null != goodsExclusiveDrawer) {
			String vehicleFullName = vehicleBizService.getVehicleName(goodsExclusiveDrawer.getVehicleStyleId());
			if(null != vehicleFullName) {
				goodsExclusiveDrawer.setVehicleStyleStr(vehicleFullName);
			}
		}
		return goodsExclusiveDrawer;
	}

	@Override
	public GoodsSubscribeDrawerVo getAppSubscribeGoods(Integer goodsId, Integer packageId, Integer storeId) throws Exception {
        //获取经销商信息
        StoreInfoBizDto storeInfoBizDto = storeBizService.getStoreInfo(storeId);
        if(null == storeInfoBizDto) {
            return null;
        }
		GoodsSubscribeDrawerVo goodsSubscribeDrawer = Convert.toGoodsSubscribeDrawerVo(goodsBizService.getAppSubscribeGoods(goodsId, packageId,storeInfoBizDto.getDealerId()));
		if(null != goodsSubscribeDrawer) {
			String vehicleFullName = vehicleBizService.getVehicleName(goodsSubscribeDrawer.getVehicleStyleId());
			if(null != vehicleFullName) {
				goodsSubscribeDrawer.setVehicleStyleStr(vehicleFullName);
			}
		}
		return goodsSubscribeDrawer;
	}

	/**
	 * 获取订阅续订商品信息
	 * 
	 * @param orderCode
	 *            订单号
	 * @return
	 * @throws Exception
	 */
	@Override
	public GoodsRenewVo getGoodsRenew(Long orderCode) throws Exception {
		GoodsRenewVo result = null;
		// 根据订单号查询订单信息
		OrderSubscribeBizDto orderSubscribeDto = orderSubscribeBizService.getOrderSubscribe(orderCode);
		if (orderSubscribeDto == null) {
			logger.error("[getGoodsRenew]订单({})不存在", orderCode);
			throw new BizException("订单不存在");
		}
		StoreInfoBizDto storeInfoBizDto = storeBizService.getStoreInfo(orderSubscribeDto.getPlaceStoreId());
		if(null == storeInfoBizDto) {
			return null;
		}
		// 获取订阅商品信息
		List<GoodsReletMileageBizDto> GoodsReletMileageBizDtos = goodsBizService
				.getGoodsMileage(orderSubscribeDto.getGoodsId(), storeInfoBizDto.getDealerId());
		if (GoodsReletMileageBizDtos == null || GoodsReletMileageBizDtos.isEmpty()) {
			logger.error("[getGoodsRenew]商品({})查询同车型商品异常", orderSubscribeDto.getGoodsId());
			throw new BizException("无续订商品");
		}

		result = new GoodsRenewVo();
		List<GoodsDrawerMileageVo> goodsDrawerMileageVos = Convert.toGoodsDrawerMileageVo(GoodsReletMileageBizDtos);
		result.setMileageList(goodsDrawerMileageVos);

		goodsReletInfo(orderSubscribeDto, result);

		return result;
	}

	/**
	 * 获取订阅加购商品信息
	 * 
	 * @param orderCode
	 *            订单号
	 * @return
	 * @throws Exception
	 */
	@Override
	public GoodsPurchaseVo getGoodsPurchase(Long orderCode) throws Exception {
		GoodsPurchaseVo result = null;
		// 根据订单号查询订单信息
		OrderSubscribeBizDto orderSubscribeDto = orderSubscribeBizService.getOrderSubscribe(orderCode);
		if (orderSubscribeDto == null) {
			logger.error("[getGoodsRenew]订单({})不存在", orderCode);
			throw new BizException("订单不存在");
		}
		StoreInfoBizDto storeInfoBizDto = storeBizService.getStoreInfo(orderSubscribeDto.getPlaceStoreId());
		if(null == storeInfoBizDto) {
			return null;
		}
		// 计算订单剩余天数
		long days = DateUtil.getDaysDiff(LocalDate.now(), orderSubscribeDto.getLeaseExpire());
		GoodsMileageSubscribeEnum goodsMileageSubscribe = null;
		if (days > 90L) {
			goodsMileageSubscribe = GoodsMileageSubscribeEnum.THREE;
		} else if (days > 30 && days <= 90L) {
			goodsMileageSubscribe = GoodsMileageSubscribeEnum.TWO;
		} else if (days <= 30L) {
			goodsMileageSubscribe = GoodsMileageSubscribeEnum.ONE;
		}

		// 获取订阅商品里程包信息
		List<GoodsMileagePackageReletBizDto> goodsMileagePackageReletBizDtos = goodsBizService
				.getGoodsMileagePackage(orderSubscribeDto.getGoodsId(), storeInfoBizDto.getDealerId(), goodsMileageSubscribe);
		if (goodsMileagePackageReletBizDtos == null || goodsMileagePackageReletBizDtos.isEmpty()) {
			logger.error("[getGoodsRenew]商品({})查询同里程包信息异常", orderSubscribeDto.getGoodsId());
			throw new BizException("无加购商品");
		}

		result = new GoodsPurchaseVo();
		result.setGoodsId(orderSubscribeDto.getGoodsId());
		List<GoodsDrawerPackageVo> packageMileages = Convert
				.toGoodsDrawerPackageVo(goodsMileagePackageReletBizDtos);
		// 加购无赠送里程
		packageMileages.stream().forEach(goodsDrawerPackageVo -> {
			goodsDrawerPackageVo.setGiftMileage(0);
		});
		result.setPackageMileageList(packageMileages);

		goodsReletInfo(orderSubscribeDto, result);


		return result;
	}

	private void goodsReletInfo(OrderSubscribeBizDto orderSubscribeDto, GoodsReletVo reletVo) {
		// 查询车型信息
		VehicleNameBizDto vehicleBizDto = vehicleBizService.getCarByModel(orderSubscribeDto.getVehicleId());
		if (vehicleBizDto == null) {
			logger.error("[getGoodsRenew]车型({})查询异常", orderSubscribeDto.getVehicleId());
			throw new BizException("商品信息异常");
		}
		// 查询车辆信息
		CarDetailBizDto carDetailBizDto = carBizService.getCarDetail(orderSubscribeDto.getCarId());
		if (carDetailBizDto == null) {
			logger.error("[getGoodsRenew]车辆({})查询异常", orderSubscribeDto.getCarId());
			throw new BizException("车辆信息异常");
		}
		// 门店id
		reletVo.setStoreId(orderSubscribeDto.getPlaceStoreId());
		// 商品名称（ 品牌+车系+车型名称）
		reletVo.setGoodsName(vehicleBizDto.getSubBrandName() + " " + vehicleBizDto.getSeriesName() + " "
				+ vehicleBizDto.getModelName());
		// 品牌名称
		reletVo.setBrandName(vehicleBizDto.getSubBrandName());
		// 车系名称
		reletVo.setSeriesName(vehicleBizDto.getSeriesName());
		// 车型名称
		reletVo.setModelName(vehicleBizDto.getModelName());
		// 车辆图片
		reletVo.setCarImg(vehicleBizDto.getWhiteFigure());
		// 品牌名
		reletVo.setBrandName(vehicleBizDto.getSubBrandName());
		// 车型ID
		reletVo.setVehicleStyleId(vehicleBizDto.getModelId());
		// 车型
		reletVo.setVehicleStyleStr(vehicleBizDto.getModelName());
		// 车牌号
		reletVo.setLicencePlate(carDetailBizDto.getLicencePlate());
		// 有效期
		reletVo.setLeaseExpire(DateUtil.formatDate(orderSubscribeDto.getLeaseExpire()));
		// 到期日
		reletVo.setLeaseExpireStr(DateUtil.formatDate(orderSubscribeDto.getLeaseExpire(), "MM月dd日") + "到期");

		// 查询订单车辆当前行驶里程
		Integer currentMileage = getCurrentMileage(carDetailBizDto.getVin());
		if (currentMileage == null) {
			logger.error("[userUsed]查询车辆({})行驶里程异常", carDetailBizDto.getVin());
			throw new BizException("查询车辆行驶里程异常");
		}
		// 剩余公里数
		Integer surplusMileage = orderSubscribeDto.getWarningMileage() - currentMileage;
		surplusMileage = surplusMileage >= 0 ? surplusMileage : 0;
		reletVo.setSurplusMileageStr("剩余里程：" + surplusMileage + "公里");
	}

	/**
	 * 获取车辆当前里程数
	 * 
	 * @param vin
	 *            车辆vin
	 * @return
	 */
	private Integer getCurrentMileage(String vin) {
		Integer result = null;
		try {
			// 车辆里程
			result = iovCarService.getCurrentMileage(vin);
		} catch (Exception e) {
			logger.error("[getCurrentMileage]获取车辆当前里程数异常：", e);
		}
		return result;
	}

	/**
	 * 获取订阅续订商品确认订单页信息
	 * 
	 * @param userId
	 *            用户id
	 * @param orderCode
	 *            订单号
	 * @param goodsId
	 *            商品id
	 * @param packageId
	 *            里程包id
	 * @return
	 * @throws Exception
	 */
	@Override
	public GoodsConfirmVo getGoodsRenewConfirm(Integer userId, Long orderCode, Integer goodsId, Integer packageId)
			throws Exception {
		// 查询订阅订单信息
		OrderSubscribeBizDto orderSubscribeBizDto = getOrderSubscribeBizDto(userId, orderCode);
		GoodsConfirmVo result = getGoodsConfirm(orderSubscribeBizDto, userId, orderCode, goodsId, packageId,
				OrderCreateTypeEnum.RENEW);
		result.setLicencePlate(null);
		return result;
	}

	/**
	 * 获取订阅加购商品确认订单页信息
	 * 
	 * @param userId
	 *            用户id
	 * @param orderCode
	 *            订单号
	 * @param goodsId
	 *            商品id
	 * @param packageId
	 *            里程包id
	 * @return
	 * @throws Exception
	 */
	@Override
	public GoodsConfirmVo getGoodsPurchaseConfirm(Integer userId, Long orderCode, Integer goodsId, Integer packageId)
			throws Exception {
		// 查询订阅订单信息
		OrderSubscribeBizDto orderSubscribeBizDto = getOrderSubscribeBizDto(userId, orderCode);
		GoodsConfirmVo result = getGoodsConfirm(orderSubscribeBizDto, userId, orderCode, goodsId, packageId,
				OrderCreateTypeEnum.PURCHASED);
		// 加购无赠送里程
		result.setGiftMileage(0);
		result.setGiftMileageStr(null);
		// 计算超里程数
		Integer beyondMileage = result.getCurrentMileage() - orderSubscribeBizDto.getWarningMileage();
		if (beyondMileage > 0) {
			// 超程
			BigDecimal beyondFee = new BigDecimal(beyondMileage * OrderConst.MILEAGE_UNIT_PRICE);
			result.getCosts().add(new CostDetailsVo("超里程费用",
					beyondMileage + "公里 * " + OrderConst.MILEAGE_UNIT_PRICE + "元/公里", beyondFee, true));

			result.setTotalFee(result.getTotalFee().add(beyondFee));
		}
		return result;
	}

    @Override
    public List<VehicleMakeVo> getBrandByStoreId(Integer storeId) throws Exception {
        //获取经销商信息
        StoreInfoBizDto storeInfoBizDto = storeBizService.getStoreInfo(storeId);
        if(null == storeInfoBizDto) {
            return null;
        }
		if(storeInfoBizDto.getIsFours()) {
			VehicleMakeDto vehicleMakeDto = vehicleMakeService.getVehicleMakeDtoById(storeInfoBizDto.getBrandId());
			return Arrays.asList(Convert.toVehicleMakeVo(vehicleMakeDto));
		}else {
			List<Integer> modelIds = goodsBizService.getModelIdByDealerId(storeInfoBizDto.getDealerId());
			List<VehicleMakeDto> vehicleMakeDtoList = vehicleBizService.getVehicleMakeByModleIds(modelIds);
			return Convert.toVehicleMakeVo(vehicleMakeDtoList);
		}
    }

	@Override
	public List<GoodsBigScreenVo> getBigScreenGoodsList(Integer storeId, Integer brandId) throws Exception  {
		//获取经销商信息
		StoreInfoBizDto storeInfoBizDto = storeBizService.getStoreInfo(storeId);
		if(null == storeInfoBizDto) {
			return null;
		}
        List<Integer> vehicleIdsList = null;
		if(storeInfoBizDto.getIsFours()) {
			brandId = storeInfoBizDto.getBrandId();
		}
		if(null != brandId) {
            List<VehicleBizDto> vehicleList = vehicleBizService.getVehicleListByMakeId(brandId);
            if((null == vehicleList)||(vehicleList.size() == 0)) {
                return null;
            }
            vehicleIdsList = new ArrayList<>();
            for(VehicleBizDto vehicleBizDto : vehicleList) {
                vehicleIdsList.add(vehicleBizDto.getId());
            }
        }
        List<GoodsBigScreenBizDto> dtoResult = goodsBizService.getBigScreenGoodsList(storeInfoBizDto.getDealerId(), vehicleIdsList);
        List<GoodsBigScreenVo> result = Convert.toGoodsBigScreenVo(dtoResult);
        if(null != result && result.size() > 0) {
            for(GoodsBigScreenVo goodsBizBizDto : result) {
                //获取车型信息
                VehicleDto vehicleDto = vehicleService.getVehicleByVehicleId(goodsBizBizDto.getVehicleStyleId());
                goodsBizBizDto.setVrLookCarUrl(vehicleDto.getVrPicUrl());
				String vehicleFullName = vehicleBizService.getVehicleName(goodsBizBizDto.getVehicleStyleId());
				goodsBizBizDto.setVehicleStyleStr(vehicleFullName);
				VehicleNameBizDto vehicleNameBizDto = vehicleBizService.getCarByModel(goodsBizBizDto.getVehicleStyleId());
				if(null != vehicleNameBizDto) {
					goodsBizBizDto.setVehicleStyleOne(vehicleNameBizDto.getSubBrandName() + " " + vehicleNameBizDto.getSeriesName());
					goodsBizBizDto.setVehicleStyleSecond(vehicleNameBizDto.getYear()+" "+vehicleNameBizDto.getModelName());
				}
                //获取车型信息

				List<VehiclePictureDto> vehiclePictureDtoList = vehiclePictureService.getVehiclePictureByVehicleId(vehicleDto.getId());
				if (vehiclePictureDtoList != null && vehiclePictureDtoList.size() > 0) {
					goodsBizBizDto.setModelImg(vehiclePictureDtoList.get(0).getServerUrl());
				}

                //获取车辆配置参数信息
                List<VehicleModelParamDto> modelParamList = vehicleParamService.getParamByModelId(goodsBizBizDto.getVehicleStyleId(), Arrays.asList("NEDC续航里程（km）", "快充时间（h）"), null);
                StringBuffer sb = new StringBuffer();
                sb.append(PowerTypeEnum.getName(vehicleDto.getPowerType()));
				Convert.getVehicleParam(modelParamList,sb);

				//获取车型下的最低价商品
				goodsBizBizDto.setMileagePrice(getBigScreenMinPrice(goodsBizBizDto));
                goodsBizBizDto.setVehicleInfo(sb.toString());
            }
        }
		return result;
	}

	private BigDecimal getBigScreenMinPrice(GoodsBigScreenVo goodsBizBizDto) {
        BigDecimal minPrice = null;
	    if((null != goodsBizBizDto)) {
            minPrice = new BigDecimal(Long.MAX_VALUE);
            List<GoodsBigScreenDrawerMileageVo> goodsBigScreenDrawerMileageList = goodsBizBizDto.getMileageList();
            if((null != goodsBigScreenDrawerMileageList)&&(goodsBigScreenDrawerMileageList.size() > 0)) {
                for(GoodsBigScreenDrawerMileageVo goodsBigScreenDrawerMileageVo : goodsBigScreenDrawerMileageList) {
                    List<GoodsBigScreenDrawerPackageVo> packageMileageList = goodsBigScreenDrawerMileageVo.getPackageMileageList();
                    if(null != packageMileageList && packageMileageList.size() > 0) {
                        for(GoodsBigScreenDrawerPackageVo goodsBigScreenDrawerPackageVo : packageMileageList) {
                            BigDecimal price = (goodsBigScreenDrawerMileageVo.getBasePrice().subtract(goodsBigScreenDrawerMileageVo.getRental()).add(goodsBigScreenDrawerPackageVo.getPackageMileagePrice()))
                                    .divide(new BigDecimal(goodsBigScreenDrawerMileageVo.getBaseMileage()+goodsBigScreenDrawerPackageVo.getPackageMileage()), 2, RoundingMode.HALF_UP);
                            if(minPrice.compareTo(price) > 0) {
                                minPrice = price;
                            }
                        }
                    }
                }
            }
            List<GoodsBigScreenDrawerSpecVo> specList = goodsBizBizDto.getSpecList();
            if((null != specList)&&(specList.size() > 0)) {
                for(GoodsBigScreenDrawerSpecVo goodsBigScreenDrawerSpecVo : specList) {
                	if(null != goodsBigScreenDrawerSpecVo) {
						if(minPrice.compareTo(goodsBigScreenDrawerSpecVo.getMonthlySupply()) > 0) {
							BigDecimal price  = goodsBigScreenDrawerSpecVo.getRental().divide(new BigDecimal(goodsBigScreenDrawerSpecVo.getLimitMileage()), 2, RoundingMode.HALF_UP);
							if(minPrice.compareTo(price) > 0) {
								minPrice = price;
							}
						}
					}
                }
            }
        }
        return minPrice;
    }


    @Override
    public List<GoodsIntroduceVo> getGoodsIntroduce(Integer goodsType) {
        List<GoodsIntroduceDto> goodsIntroduceList = goodsIntroduceService.getGoodsIntroduce(GoodsTypeIntroduceEnum.getName(goodsType));
        return Convert.toGoodsIntroduceVo(goodsIntroduceList);
    }

	private GoodsConfirmVo getGoodsConfirm(OrderSubscribeBizDto orderSubscribeBizDto, Integer userId, Long orderCode,
			Integer goodsId, Integer packageId, OrderCreateTypeEnum type) throws Exception {
		GoodsConfirmVo result = null;
		// 查询商品信息
		GoodsOrderBizDto goods = getGoodsOrderBizDto(goodsId, packageId);
		// 数据转换
		result = Convert.toGoodsConfirmVo(orderSubscribeBizDto, goods, type);
		// 查询车辆信息
		CarDetailBizDto carDetailBizDto = carBizService.getCarDetail(orderSubscribeBizDto.getCarId());
		// 车牌号
		result.setLicencePlate(carDetailBizDto.getLicencePlate());
		// 当前行驶里程
		result.setCurrentMileage(getCurrentMileage(carDetailBizDto.getVin()));
		// 查询门店信息
		StoreDto storeDto = storeService.getStoreById(orderSubscribeBizDto.getPlaceStoreId());
		// 门店名称
		result.setStoreName(storeDto.getShortName());
		// 查询车型信息
		VehicleNameBizDto vehicleBizDto = vehicleBizService.getCarByModel(orderSubscribeBizDto.getVehicleId());
		// 商品名称（ 品牌+车系+车型名称）
		result.setGoodsName(vehicleBizDto.getSubBrandName() + " " + vehicleBizDto.getSeriesName() + " "
				+ vehicleBizDto.getModelName());
		// 品牌名称
		result.setBrandName(vehicleBizDto.getSubBrandName());
		// 车系名称
		result.setSeriesName(vehicleBizDto.getSeriesName());
		// 车型名称
		result.setModelName(vehicleBizDto.getModelName());
		// 车辆图片
		result.setCarImg(vehicleBizDto.getWhiteFigure());

		return result;
	}

	/**
	 * 查询订阅订单信息
	 * 
	 * @param userId
	 * @param orderCode
	 * @return
	 */
	private OrderSubscribeBizDto getOrderSubscribeBizDto(Integer userId, Long orderCode) {
		// 根据订单号查询订阅里程订单信息
		OrderSubscribeBizDto result = orderSubscribeBizService.getOrderSubscribe(orderCode);
		if (result == null) {
			logger.error("[getOrderSubscribeBizDto]根据订单号(" + orderCode + ")查询订单异常，订单不存在");
			throw new BizException("查询失败，订单不存在");
		} else if (!result.getUserId().equals(userId)) {
			logger.error("[getOrderSubscribeBizDto]根据订单号(" + orderCode + ")、用户(" + userId + ")查询订单异常，订单用户信息不匹配");
			throw new BizException("查询失败，订单不存在");
		}

		return result;
	}

	/**
	 * 查询商品信息
	 * 
	 * @param goodsId
	 * @param packageId
	 * @return
	 * @throws Exception
	 */
	private GoodsOrderBizDto getGoodsOrderBizDto(Integer goodsId, Integer packageId) throws Exception {
		// 查询商品信息
		GoodsOrderBizDto result = goodsBizService.getGoodsForOrder(goodsId, packageId);
		if (result == null) {
			logger.error("[getGoodsOrderBizDto]商品(" + goodsId + ")不存在");
			throw new BizException(GoodsExceptionCodeEnum.NONENTITY.getCode(),
					GoodsExceptionCodeEnum.NONENTITY.getMessage());
		}
		return result;
	}
}
